package com.daykw.xiaohongshu.task;

import java.util.List;

import org.apache.log4j.Logger;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;

import com.daykw.xiaohongshu.model.Ips;
import com.daykw.xiaohongshu.util.Const;
import com.daykw.xiaohongshu.util.EhcacheUtils;
import com.daykw.xiaohongshu.util.IPPoolMap;
import com.daykw.xiaohongshu.util.SpringContextHolder;

public class IpPoolTask implements Runnable {
	private static Logger logger = Logger.getLogger(IpPoolTask.class);

	@Override
	public void run() {

		// logger.info("******************************************************************");
		// logger.info("******************************************************************");
		// logger.info("***********ip队列长度:" + IPPoolMap.getQueue().size() +
		// "****************");
		// logger.info("******************************************************************");
		// logger.info("******************************************************************");
		this.getIpPool();
		// this.setArticleTask();

	}

	private void getIpPool() {
		NutDao dao = SpringContextHolder.getBean("dao");
		int tcount = (Const.PAGE_THREAD + Const.ARTICLE_THREAD + Const.COMMENT_THREAD) * Const.IP_COUNT;
		
		String querySql = "SELECT * FROM 	t_ips WHERE	id >= (	(SELECT MAX(id) FROM t_ips) - (SELECT MIN(id) FROM t_ips)	) * RAND() + (SELECT MIN(id) FROM t_ips) LIMIT "
				+ tcount;
		Sql sql = Sqls.queryEntity(querySql);
		sql.setCallback(Sqls.callback.entities());
		sql.setEntity(dao.getEntity(Ips.class));
		dao.execute(sql);
		List<Ips> list = sql.getList(Ips.class);

		for (Ips ip : list) {
			if (!EhcacheUtils.getInstance().containsKey(ip.getIps())) {
				IPPoolMap.getQueue().offer(ip);
			}

		}
		logger.info("***********获取" + IPPoolMap.getQueue().size() + "个IP*************");
	}

}
